//
//  RecentActivityViewController.m
//  ITHome
//
//  Created by lanou3g on 15/7/15.
//  Copyright (c) 2015年 YAX. All rights reserved.
//

#import "RecentActivityViewController.h"
#import "RecentActivityModel.h"
#import "YiDongWebViewController.h"
#define KYIDONG @"http://c.m.163.com/nc/article/list/T1351233117091/0-20.html"

#define kRecentTable @"RecentTabel"            //移动互联 离线表


@interface RecentActivityViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)NSMutableArray *modelArray;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,assign)int pages;



@end

@implementation RecentActivityViewController

- (NSMutableArray *)modelArray
{
    if (!_modelArray) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

- (void)viewDidLoad
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 30 - 64 - 49) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_tableView];
    [super viewDidLoad];
    
    // 自动刷新
    [self recentDownRefresh];
    
//      [self getRequest];

    // 下拉刷新
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(recentDownRefresh)];
    
    // 上拉提载
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
}

// 下拉刷新
- (void)recentDownRefresh
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    // 如果有网
    if ([r currentReachabilityStatus] != NotReachable)
    {

        [FMDBManage deleteAllDatabaseTable:kRecentTable];   //刷新成功后再移除数据库中数据。
    }
    else
    {
        [ProgressHUD progressHUD:self.view labelText:@"加载失败了😭, 请检查网络"];
    }
    [self getRequest];
}

// 上拉提载
- (void)upRefresh
{
    
    
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    // 如果有网才能下拉加载(防止崩溃)
    if ([r currentReachabilityStatus] != NotReachable)
    {
        // 数据解析
        [self getUPRequest];
    }
    else
    {
        [ProgressHUD progressHUD:self.view labelText:@"加载失败了😭,请检查网络"];
        // 停止刷新
        [self.tableView.footer endRefreshing];
    }
    
}

// 解析
- (void)getRequest
{

    [FMDBManage createDatabaseTabel:kRecentTable];
    
    NSArray *arr = [FMDBManage selectAllRecentCacheTabel:kRecentTable];
    if (arr.count != 0)
    {
        self.modelArray = [arr mutableCopy];
    }
    else
    {
        [self.modelArray removeAllObjects];
       [LORequestManger GET:KYIDONG success:^(id response) {
           NSDictionary *bigDic = (NSDictionary *)response;
           NSArray *bigArray = bigDic[@"T1351233117091"];
           for (NSDictionary *dict in bigArray) {
               RecentActivityModel *model = [RecentActivityModel modelWithDict:dict];
               model.featureImageUrl = model.imgsrc;
               
               // 插入数据
               [FMDBManage insertCacheTable:kRecentTable Title:model.title created_at:model.lmodify replies_count:[NSString stringWithFormat:@"%d",model.replyCount] featureImageUrl:model.featureImageUrl];
               
               [self.modelArray addObject:model];
           }
           [self.tableView reloadData];
           
           [self.tableView.header endRefreshing];
       } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [ProgressHUD progressHUD:self.view labelText:@"加载失败,请检查网络"];
       }];
    }
    
}

// 上拉提载
- (void)getUPRequest
{
    self.pages += 20;
    NSString *url = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/list/T1351233117091/%d-20.html",self.pages];
    [LORequestManger GET:url success:^(id response) {
        NSDictionary *bigDic = (NSDictionary *)response;
        NSArray *bigArray = bigDic[@"T1351233117091"];
        for (NSDictionary *dict in bigArray) {
            RecentActivityModel *model = [RecentActivityModel modelWithDict:dict];
            [self.modelArray addObject:model];
        }
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [ProgressHUD progressHUD:self.view labelText:@"加载失败"];
    }];
    [self.tableView.footer endRefreshing];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.modelArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView registerClass:[ITHomePublicTableViewCell class] forCellReuseIdentifier:@"recent"];
    ITHomePublicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"recent"];
    if (self.modelArray.count != 0) {
        RecentActivityModel *model = self.modelArray[indexPath.row];
        [cell setYiDongModel:model];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kScreenIp6(90);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    YiDongWebViewController *web = [[YiDongWebViewController alloc]init];
    RecentActivityModel *model = self.modelArray[indexPath.row];
    web.urlString = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/%@/full.html",model.docid];
    web.commentsCount = [NSString stringWithFormat:@"%d",model.replyCount];
    web.docid = model.docid;
    web.url_3w = model.url_3w;
    web.Mytitle = model.title;
    UIImageView *imageView = [[UIImageView alloc]init];
    [imageView sd_setImageWithURL:[NSURL URLWithString:model.imgsrc]];
    web.myImage = imageView.image;
        
    // 模态过去
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:web];
    nav.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:nav animated:YES completion:nil];
    
}

#pragma mark - 内容警告提示
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    [[SDImageCache sharedImageCache] clearMemory];
}

@end
